<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="users" border highlight-current-row v-loading="listLoading" style="width: 100%;">
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="uid" label="用户ID" width="140" sortable>
      </el-table-column>
      <el-table-column prop="name" label="用户姓名" width="140">
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="140">
      </el-table-column>
      <el-table-column prop="active" label="状态" width="100" :formatter="formatStatus" sortable>
      </el-table-column>
      <el-table-column prop="company" label="公司" min-width="220">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--编辑界面-->
    <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户ID" prop="uid">
          <el-input v-model="editForm.uid" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="status">
          <el-input v-model="editForm.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="active">
          <el-select v-model="editForm.active" placeholder="请选择">
            <el-option v-for="item in statusEmu" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司" prop="address">
          <el-input v-model="editForm.company" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="address">
          <el-input v-model="editForm.phone" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="address">
          <el-input v-model="editForm.description" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="用户ID" prop="uid">
          <el-input v-model="addForm.uid" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="uid">
          <el-select v-model="addForm.role" placeholder="请选择">
            <el-option v-for="item in roleEmu" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input type="password" v-model="addForm.password2" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="公司" prop="company">
          <el-input v-model="addForm.company"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import md5 from 'js-md5'

export default {
  data() {
    return {
      users: [],
      listLoading: false,

      //编辑界面
      editFormVisible: false,
      editLoading: false,
      editFormRules: {
        active: [
          { required: true, message: '请输入用户状态', trigger: 'blur' }
        ]
      },
      editForm: {
        uid: '',
        name: '',
        active: '',
        company: '',
        address: '',
        phone: '',
        description: '',
        logo_url: ''
      },

      //新增界面
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        uid: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择用户角色', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入公司地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: this.confirmPassword, trigger: 'blur' }
        ]
      },
      addForm: {
        uid: '',
        name: '',
        role: '04',
        company: '',
        address: '',
        phone: '',
        description: '',
        password: '',
        password2: '',
        logo_url: ''
      },
      roleEmu: [
        {
          key: '01',
          value: '设备'
        }, {
          key: '02',
          value: '管理员'
        }, {
          key: '03',
          value: '超级用户'
        }, {
          key: '04',
          value: '普通用户'
        }
      ],
      statusEmu: [
        {
          key: '1',
          value: '正常'
        }, {
          key: '2',
          value: '关闭'
        }
      ]
    }
  },
  methods: {
    formatRole: function(row, column) {
      for (let i = 0; i < this.roleEmu.length; i++) {
        if (row.role == this.roleEmu[i].key) {
          return this.roleEmu[i].value
        }
      }
      return '未知类型'
    },
    formatStatus: function(row, column) {
      for (let i = 0; i < this.statusEmu.length; i++) {
        if (row.active == this.statusEmu[i].key) {
          return this.statusEmu[i].value
        }
      }
      return '未知类型'
    },
    confirmPassword: function(rule, value, callback) {
      if (value != this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    },
    //获取用户列表
    getUsers: function() {
      this.listLoading = true

      let token = sessionStorage.getItem('token')
      let params = this.formatHttpGetParams({ token: token })
      let path = 'api/users/query'
      this.$http.get(this.$store.state.domain + path + params).then(function(res) {
        if (res.body.respCode == '0000') {
          this.users = res.body.data
        } else {
          if (res.body.respMsg != null) {
            alert(res.body.respMsg)
          } else {
            alert('后台未知异常，请与管理员联系')
          }
        }
        this.listLoading = false
      }, function() {
        alert('网络请求处理失败')
        this.listLoading = false
      })
    },
    //删除
    handleDel: function(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true

        let data = new Object()
        data.uid = row.uid

        let token = sessionStorage.getItem('token')
        let params = this.formatHttpGetParams({ token: token })
        let path = 'api/users/delete'
        this.$http.post(this.$store.state.domain + path + params, JSON.stringify(data), { emulateJSON: true })
          .then(function(res) {
            if (res.body.respCode == '0000') {
              alert('删除成功！')
              this.getUsers()
            } else {
              if (res.body.respMsg != null) {
                alert(res.body.respMsg)
              } else {
                alert('后台未知异常，请与管理员联系')
              }
            }
            this.listLoading = false
          },
          function(error) {
            alert('网络请求处理失败')
            this.listLoading = false
          })
      })
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      this.editForm = Object.assign({}, row)
      this.editForm.role = '04'
    },
    //显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.addForm = {
        uid: '',
        name: '',
        role: '04',
        company: '',
        address: '',
        phone: '',
        description: '',
        password: '',
        password2: '',
        logo_url: ''
      }
    },
    //编辑
    editSubmit: function() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true

            let data = new Object()
            data.uid = this.editForm.uid
            data.active = this.editForm.active

            let token = sessionStorage.getItem('token')
            let params = this.formatHttpGetParams({ token: token })
            let path = 'api/users/update'
            this.$http.post(this.$store.state.domain + path + params, JSON.stringify(data), { emulateJSON: true })
              .then(function(res) {
                if (res.body.respCode == '0000') {
                  alert('修改成功！')
                  this.$refs['editForm'].resetFields()
                  this.editFormVisible = false
                  this.editLoading = false
                  this.getUsers()
                } else {
                  if (res.body.respMsg != null) {
                    alert(res.body.respMsg)
                  } else {
                    alert('后台未知异常，请与管理员联系')
                  }
                  this.$refs['editForm'].resetFields()
                  this.editLoading = false
                }
              },
              function(error) {
                alert('网络请求处理失败')
                this.$refs['editForm'].resetFields()
                this.editLoading = false
              })
          })
        }
      })
    },
    //新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true

            let data = new Object()
            data.uid = this.addForm.uid
            data.password = md5(this.addForm.password)
            data.name = this.addForm.name
            data.role_id = this.addForm.role
            data.company = this.addForm.company
            data.address = this.addForm.address
            data.phone = this.addForm.phone
            data.logo_url = this.addForm.logo_url
            data.description = this.addForm.description

            let token = sessionStorage.getItem('token')
            let params = this.formatHttpGetParams({ token: token })
            let path = 'api/users/add'
            this.$http.post(this.$store.state.domain + path + params, JSON.stringify(data), { emulateJSON: true })
              .then(function(res) {
                if (res.body.respCode == '0000') {
                  alert('添加成功！')
                  this.$refs['addForm'].resetFields()
                  this.addFormVisible = false
                  this.addLoading = false
                  this.getUsers()
                } else {
                  if (res.body.respMsg != null) {
                    alert(res.body.respMsg)
                  } else {
                    alert('后台未知异常，请与管理员联系')
                  }
                  this.addLoading = false
                }
              },
              function(error) {
                alert('网络请求处理失败')
                this.addLoading = false
              })
          })
        }
      })
    }
  },
  mounted() {
    this.getUsers()
  }
}
</script>

<style scoped>

</style>